//
//  GemaViewMode.swift
//  JunYiProject
//
//  Created by xiaogxjkz on 2021/6/10.
//

import UIKit

class GameViewModel: BaseViewModel {
    
    
    //MARK: - lazy load
    /// 游戏行情数据加载
    lazy var gameMarketListCommand:RACCommand = {
        let _com = RACCommand.init {[weak self] (input:Any?) -> RACSignal? in
            guard let self = self else { return nil }
            
            let signal:RACSignal = RACSignal.createSignal {[weak self](subscriber:RACSubscriber?) -> RACDisposable? in
                guard let self = self else { return nil }
                guard let (_symbol,_scale,_datalen) = input as? (String,Int,Int) else {
                    //默认
                    self.gameMarketListLoadFor(withRACSubscriber: subscriber)
                    return nil
                }
                
                self.gameMarketListLoadFor(Code: _symbol,
                                           andScale: _scale,
                                           andDataLength: _datalen,
                                           withRACSubscriber: subscriber)
                return nil
            }
            
            return signal
        }
        
        return _com!
    }()
    
    
    /// 副图指标切换
    lazy var gameMarketKpiChangeCommand:RACCommand = {
        let _com = RACCommand.init {[weak self] (input:Any?) -> RACSignal? in
            guard let self = self else { return nil }
            
            let signal:RACSignal = RACSignal.createSignal {[weak self](subscriber:RACSubscriber?) -> RACDisposable? in
                guard let self = self else { return nil }
                guard let (_currentIndex,_title) = input as? (Int,String) else {
                    return nil
                }
                
                subscriber?.sendNext((_currentIndex,_title))
                subscriber?.sendCompleted()
                
                return nil
            }
            
            return signal
        }
        
        return _com!
    }()
}


//MARK: -
extension GameViewModel {
    
    //MARK: - 游戏行情数据
    /// 行情数据加载
    /// - Parameters:
    ///   - _c: String 股票代码(sh000001 上证指数)
    ///   - _s: Int K线数据(5,15,30,60)
    ///   - _dl: Int 获取数据长度，最大1023
    ///   - subscriber: <#subscriber description#>
    private func gameMarketListLoadFor(Code _c:String = "sh000001",
                                       andScale _s:Int = 5,
                                       andDataLength _dl:Int = 120,
                                       withRACSubscriber subscriber:RACSubscriber? = nil) {
        
        let strUrl:String = UrlSetting.gameMarketList
        
        let dicParams:[String:Any] = [
            "symbol":_c,
            "scale":_s,
            "ma":"no",
            "datalen":_dl
        ]
        
        CMRequest.shareInstance().getRequestFinishData(strUrl: strUrl,
                                                       withParameters: dicParams) { (_responseData:Any?) in
            guard let _arrTemp = _responseData as? [[String:Any]],_arrTemp.count > 0 else {
                let _arrLocal = self.getLocalGameMarketData()
                subscriber?.sendNext(_arrLocal)
                subscriber?.sendCompleted()
                return
            }
            
            //[S] 返回数据
            if let _data = Utils.shareInstance().getJsonDataFor(Any: _arrTemp) {
                //[S]缓存到本地
                DispatchQueue.global().async {
                    UserDefaults.standard.setValue(_data, forKey: MarketSetting.gameMarketList)
                    UserDefaults.standard.synchronize()
                }
                //[E]
                
                do{
                    let decoder = JSONDecoder.init()
                    let result = try decoder.decode([GameMarketModel].self, from: _data)
                    
                    if result.count > 0 {
                        subscriber?.sendNext(result)
                    }
                    else{
                        let _arrLocal = self.getLocalGameMarketData()
                        subscriber?.sendNext(_arrLocal)
                    }
                }
                catch(let _error){
                    print(_error)
                    let _arrLocal = self.getLocalGameMarketData()
                    subscriber?.sendNext(_arrLocal)
                }
            }
            //[E]
            
            subscriber?.sendCompleted()
        }
    }
    
    
    /// 获取本地存储的离线数据
    /// - Returns: [GameMarketModel]
    private func getLocalGameMarketData() -> [GameMarketModel] {
        if let _data:Data = UserDefaults.standard.data(forKey: MarketSetting.gameMarketList) {
            do{
                let decoder = JSONDecoder.init()
                let result = try decoder.decode([GameMarketModel].self, from: _data)
                return result
            }
            catch(let _error){
                print(_error)
                return [GameMarketModel]()
            }
        }
        
        return [GameMarketModel]()
    }
}
